package handlers

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"xiao-hong-book/cache"
	"xiao-hong-book/models"
	"xiao-hong-book/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	redis_key := "login_error" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}

	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "没有找到该用户",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	token := pkg.JwtHandler(strconv.Itoa(int(user.ID)))

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"token": token,
	})
	return

}

func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))

	data := models.UserRole{

		Uid: uid,
		Rid: rid,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户角色关联失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "用户角色关联成功",
	})
	return

}

func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	data := models.RoleNode{

		Rid: rid,
		Nid: nid,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "角色权限关联失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "角色权限关联成功",
	})
	return

}

func UserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var count int64
	models.DB.Model(&models.User{}).Count(&count)

	var user []models.User
	err := models.DB.Offset(offset).Limit(size).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "展示失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": gin.H{
			"count": count,
			"data":  user,
		},
	})
	return

}

func Detail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))

	var user models.User
	err := models.DB.Where("id = ?", id).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查找详情失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查找成功",
		"data": user,
	})
	return

}
